from datetime import timedelta
from django.db import models, transaction
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny,IsAuthenticated
from drf_yasg.utils import swagger_auto_schema
from .models import Order, OrderLog
from .serializers import (
    OrderListSerializer,
    OrderCreateSerializer,
    OrderStatusSerializer,
    ReviewSerializer
)
from django.shortcuts import get_object_or_404
from django.utils import timezone
from products.models import Product
from .models import *
from rest_framework import viewsets
from .docs import *

class OrderViewSet(viewsets.ModelViewSet):
    lookup_field = 'order_code'  # 修改默认的查询字段
    lookup_url_kwarg = 'order_code'  # 修改URL参数名称
    swagger_tags = ['orders']
    queryset = Order.objects.all()
    permission_classes = [IsAuthenticated]
    def get_serializer_class(self):
        """根据不同的操作返回对应的序列化器"""
        if self.action == 'create':
            return OrderCreateSerializer
        elif self.action == 'update_status':
            return OrderStatusSerializer
        return OrderListSerializer
    
    def get_queryset(self):
        """获取订单查询集"""
        queryset = Order.objects.all()
        
        if not self.request.user.is_authenticated:
            return Order.objects.none()
            
        return queryset

    def get_serializer_context(self):
        """添加额外的上下文信息"""
        context = super().get_serializer_context()
        context['role'] = self.request.query_params.get('role', 'buyer')
        return context
    
    @swagger_auto_schema(**OrderViewsetDocs['list'])
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        
        if request.user.is_authenticated:
            role = request.query_params.get('role', 'buyer')
            if role == 'seller':
                queryset = queryset.filter(seller=request.user)
            else:
                queryset = queryset.filter(buyer=request.user)

        # 状态过滤
        status_filter = request.query_params.get('status')
        if status_filter:
            queryset = queryset.filter(status=status_filter)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


    @swagger_auto_schema(**OrderViewsetDocs['retrieve'])
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)  # 直接返回序列化结果

    
    @swagger_auto_schema(**OrderViewsetDocs['create'])
    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            product = serializer.validated_data['product']
            try:
                product = Product.objects.select_for_update().get(
                    id=product.id,
                    status__in=[0, 1]
                )
            except Product.DoesNotExist:
                return Response(
                    {"code": "PRODUCT_NOT_FOUND", "message": "商品不可用"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 提前保存旧状态
            old_status = product.status
            # 更新商品状态
            product.status = 2
            product.save(update_fields=['status'])
            
            # 创建订单
            order = serializer.save()

            # 记录日志
            OrderLog.objects.create(
                order=order,
                action='create',
                operator=request.user,
                detail={
                    "product_id": product.id,
                    "old_status": old_status,
                    "new_status": 2
                },
                ip_address=request.META.get('REMOTE_ADDR')
            )

            return Response(
                OrderListSerializer(order).data,
                status=status.HTTP_201_CREATED
            )
    
    @swagger_auto_schema(**OrderViewsetDocs['update_status'])
    @action(detail=True, methods=['patch'], url_path='status')
    def update_status(self, request, order_code=None):
        with transaction.atomic():
            # 获取订单时就加锁
            order = Order.objects.select_for_update().get(order_code=order_code)
            product = Product.objects.select_for_update().get(id=order.product.id)
            new_status = request.data.get('status')

            # 角色验证
            is_seller = order.seller == request.user
            is_buyer = order.buyer == request.user

            # 状态流转规则
            valid_transitions = {
                'seller': {
                    1: [2, 4],  # 待发货 → 待收货/取消
                },
                'buyer': {
                    0: [1, 4],  # 待支付 → 待发货/取消
                    1: [4],     # 待发货 → 取消 (新增这个状态)
                    2: [3],     # 待收货 → 完成
                }
            }

            # 验证权限
            if is_seller and new_status not in valid_transitions['seller'].get(order.status, []):
                return Response({"detail": "卖家不允许此操作"}, status=status.HTTP_403_FORBIDDEN)
            
            if is_buyer and new_status not in valid_transitions['buyer'].get(order.status, []):
                return Response({"detail": "买家不允许此操作"}, status=status.HTTP_403_FORBIDDEN)

            # 如果是取消订单,恢复商品状态为已上架
            if new_status == 4:
                product.status = 1
                product.save()

            # 更新订单状态
            order.status = new_status
            order.save()

            # 记录日志
            OrderLog.objects.create(
                order=order,
                action='cancel' if new_status == 4 else 'status_change',
                operator=request.user,
                detail=request.data.get('reason', None),
                ip_address=request.META.get('REMOTE_ADDR')
            )

            return Response({'status': 'success'})

    @swagger_auto_schema(**OrderViewsetDocs['initiate_payment'])
    @action(detail=True, methods=['post'], url_path='pay')
    def initiate_payment(self, request, order_code=None):
        """简化版支付接口，直接完成支付"""
        with transaction.atomic():
            # 获取并锁定订单和商品
            order = self.get_object()
            product = Product.objects.select_for_update().get(pk=order.product.id)

            # 验证订单状态
            if order.status != 0:
                return Response(
                    {"error": "只有待支付订单可支付"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 更新订单状态
            order.status = 1  # 待发货
            order.payment_status = 'paid'
            order.payment_time = timezone.now()
            order.save(update_fields=['status', 'payment_status', 'payment_time'])

            # 更新商品状态（保持交易中）
            product.status = 2
            product.save(update_fields=['status'])

            # 记录操作日志
            OrderLog.objects.create(
                order=order,
                action='pay',
                operator=request.user,
                detail={
                    "amount": order.snapshot_price,
                    "payment_method": "模拟支付"
                },
                ip_address=request.META.get('REMOTE_ADDR')
            )
            return Response({
                "status": "success",
                "order_status": order.status
            })

    @swagger_auto_schema(**OrderViewsetDocs['complete_order'])
    @action(detail=True, methods=['post'], url_path='complete')
    def complete_order(self, request, order_code=None):
        """将订单标记为已完成"""
        with transaction.atomic():
            # 获取并锁定订单和商品
            order = self.get_object()
            product = Product.objects.select_for_update().get(pk=order.product.id)

            # 验证订单状态
            if order.status != 2:
                return Response(
                    {"error": "只有待收货订单可完成"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 更新订单状态
            order.status = 3  # 已完成
            order.complete_time = timezone.now()
            order.save(update_fields=['status', 'complete_time'])

            # 更新商品状态（数值3对应已完成）
            product.status = 3
            product.save(update_fields=['status'])

            # 记录操作日志
            OrderLog.objects.create(
                order=order,
                action='complete',
                operator=request.user,
                detail={
                    "operation": "确认收货",
                    "location": order.pickup_location
                },
                ip_address=request.META.get('REMOTE_ADDR')
            )

            return Response({
                "status": "success",
                "product_status": product.status
            })

    
    # def get_reviews(self, request, order_code=None):
    #     """订单维度的评论查询"""
    #     order = self.get_object()
    #     reviews = order.reviews.all().order_by('-review_time')
    #     page = self.paginate_queryset(reviews)
    #     serializer = ReviewSerializer(page, many=True)
    #     return self.get_paginated_response(serializer.data)


# ====================== 支付回调 ======================
class PaymentCallbackView(APIView):
    permission_classes = [AllowAny]

    @swagger_auto_schema(**PaymentCallbackDocs['post'])
    def post(self, request):
        with transaction.atomic():
            # 获取并锁定订单记录
            order = get_object_or_404(
                Order.objects.select_for_update(),
                order_code=request.data['order_code']
            )

            if request.data['success']:
                # 支付成功处理
                order.status = 1  # 待发货
                order.payment_time = timezone.now()
                order.product.status = 2  # 保持交易中状态（数值2）
                log_action = 'pay_success'
            else:
                # 支付失败处理
                order.status = 4  # 已取消
                order.product.status = 1  # 恢复商品可购买状态（数值1）
                log_action = 'pay_fail'

            # 原子化保存
            order.product.save(update_fields=['status'])
            order.save()

            # 记录操作日志
            OrderLog.objects.create(
                order=order,
                action=log_action,
                operator=order.buyer,
                detail=request.data,
                ip_address=request.META.get('REMOTE_ADDR')
            )

            return Response({"status": "success"})


class ReviewViewSet(viewsets.ModelViewSet):
    serializer_class = ReviewSerializer
    permission_classes = [IsAuthenticated]
    http_method_names = ['get', 'post', 'patch', 'delete']  # 禁用put

    
    def get_queryset(self):
        """数据范围控制：用户只能看到自己的评价或卖家的评价"""
        user = self.request.user
        if not user.is_authenticated:
            return Reviews.objects.none()
        if user.is_staff:
            return Reviews.objects.all()
        
        return Reviews.objects.filter(
            models.Q(buyer=user) | models.Q(order__seller=user)
        )
    
    def list(self, request, *args, **kwargs):
        # 修正后的列表方法（避免直接修改 self.queryset）
        order_code = request.query_params.get('order')
        queryset = self.filter_queryset(self.get_queryset())
        
        if order_code:
            queryset = queryset.filter(order__order_code=order_code)
            
        # 添加默认排序
        queryset = queryset.order_by('-review_time')
        
        # 分页处理
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


    @swagger_auto_schema(**ReviewViewsetDocs['create'])
    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            # 原子化操作：锁定订单记录
            order_id = request.data.get('order')
            try:
                order = Order.objects.select_for_update().get(
                    pk=order_id,
                    status=3,  # 硬编码状态值3
                    buyer=request.user
                )
            except Order.DoesNotExist:
                return Response(
                    {"code": "order_invalid", "message": "订单不可用"},
                    status=status.HTTP_400_BAD_REQUEST
                )

            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save(buyer=request.user)

            return Response(serializer.data, status=status.HTTP_201_CREATED)

    @swagger_auto_schema(**ReviewViewsetDocs['update'])
    def update(self, request, *args, **kwargs):
        """仅允许修改内容，不开放其他字段修改"""
        partial = kwargs.pop('partial', True)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)



